from study.models import users
# from website.study.models import users
from django.shortcuts import render_to_response
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from website.utils.responseUtils import JsonResponseDiy


def login_user(request):
	page = request.GET.get('next')

	return render_to_response('study1.html', locals())


@csrf_exempt
def create_user(request):
	print(request.POST)
	username = request.POST.get('username', '')
	age = request.POST.get('age', '')
	tel = request.POST.get('tel', '')

	resultJson = {"success": False}
	try:
		# u = users(name=username, age=age, tel=tel)
		# u.save()
		users.objects.create(name=username, age=int(age), tel=int(tel))
		resultJson["success"] = True
	except Exception as e:
		print(e)

	response = JsonResponse(resultJson, safe=False)
	return JsonResponseDiy(response)


@csrf_exempt
def get_user(request):
	# print(request.POST)
	username = request.POST.get('username', '')
	print(request.POST)
	bjson = request.body  # recv json body
	print(str(bjson, encoding="utf-8"))

	# resultJson = {"success": False}
	resultJson = {}
	resultJson['success'] = True
	try:
		# u = users(name=username, age=age, tel=tel)
		# u.save()
		if username != "":
			u = users.objects.filter(name=username).all()
		else:
			u = users.objects.all()
		result_list = []
		for i in u:
			result_list.append(i.to_dict())
		resultJson["data"] = result_list
		resultJson['success'] = True

	# resultJson["success"] = True
	except Exception as e:
		print(e)

	response = JsonResponse(resultJson, safe=False)
	# response["Access-Control-Allow-Origin"] = "*"
	# response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
	# response["Access-Control-Max-Age"] = "1000"
	# response["Access-Control-Allow-Headers"] = "*"
	return JsonResponseDiy(response)
